﻿using System;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Controllers;
using Common.Logging;
using In.Api.Dto.HisWs;
using Newtonsoft.Json;
using OutDbContext;
using User.Api.Dto.Queue;
using User.Api.Helpers;
using User.Api.HttpClients;

namespace User.Api.Controllers
{
    public class QueueController : ApiController
    {
        private static readonly ILog Logger = LogManager.GetLogger(typeof(QueueController));
        private FsssdqfybjyEntities _ctx;

        protected override void Initialize(HttpControllerContext controllerContext)
        {
            _ctx = new FsssdqfybjyEntities();
            base.Initialize(controllerContext);
        }

        protected override void Dispose(bool disposing)
        {
            _ctx.Dispose();
            base.Dispose(disposing);
        }

        /// <summary>
        /// 获取就诊队列
        /// </summary>
        /// <param name="cardId"></param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("GetQueues")]
        public GetQueuesResponse GetQueues(int cardId)
        {
            var azUser = AzUser.GetInApi(Request);

            var card = _ctx.HospCards.FirstOrDefault(x => x.Id == cardId && x.WxUserId == azUser.UserId);
            if (card == null)
            {
                return new GetQueuesResponse
                {
                    ResultCode = "1",
                    ResultMsg = "找不到卡号"
                };
            }

            var request = new Request4GetWaitNum();
            request.CardNo = card.CardNo;

            Response4GetWaitNum response;
            try
            {
                var httpClient = InHttpClient.GetClient();
                var responseMsg = httpClient.PostAsJsonAsync("HisWs/GetWaitNum", request).Result;
                responseMsg.EnsureSuccessStatusCode();
                response = responseMsg.Content.ReadAsAsync<Response4GetWaitNum>().Result;
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("调用院内队列信息出错,信息：{0}", JsonConvert.SerializeObject(ex));

                return new GetQueuesResponse
                {
                    ResultCode = "2",
                    ResultMsg = "获取院内队列信息超时"
                };
            }

            if (response.ResultCode != "0")
            {
                return new GetQueuesResponse
                {
                    ResultCode = "2",
                    ResultMsg = response.ResultDesc
                };
            }

            return new GetQueuesResponse
            {
                ResultCode = "0",
                ResultMsg = "",
                Queues = response.WaitNumInfoList.Select(x => new GetQueuesResponse.Queue
                {
                    DeptName = x.DeptName,
                    DoctorName = x.DoctorName,
                    WaitNo = x.WaitNo
                }).ToList()
            };
        }
    }
}
